const Fork = require('../lib/worker');
const path = require('path');
const chalk = require('chalk');
const fs = require('fs').promises;
const isExist = require('../lib/helper/utils').isExist;
const util = require('./util');

function results(...args) {
  const arr = ['clone', 'tag', 'install', 'cmd'];
  return args.map((el, index) => util[arr[index]](el)).join(' ');
}

module.exports = function (REPO_ROOT, flag) {
  const repoName = 'tagup-test1';
  const f1 = Fork.default();
  f1.on('message', async (data) => {
    if (data.message === 'EXIT') {

      const p1 = path.join(REPO_ROOT, repoName, '2.txt');
      if (await isExist(p1)) {
        const content = await fs.readFile(p1, 'utf8');

        if (content === 'c') {
          console.log(repoName, results(1, 0, 0, 0));
        } else if (content === 'b') {
          console.log(repoName, results(1, 1, 1, 1));
        } else if (content === 'a') {
          if (await isExist(path.join(REPO_ROOT, repoName, '/node_modules'), true)) {
            console.log(repoName, results(1, 1, 1, 0));
          } else {
            console.log(repoName, results(1, 1, 0, 0));
          }
        } else {
          console.log(repoName, results(1, 0, 0, 0));
        }
      } else {
        console.log(repoName, results(0, 0, 0, 0));
      }
      f1.kill(9);
      flag.count++;
    }
  }).send({
    options: { sshUrl: 'git@gitee.com:satrong/tagup-test1.git' },
    REPO_NAME: repoName,
    TAG: 'v1.0.0',
    REPO_ROOT,
    ROOT: __dirname,
  });
}